package com.info.springmongo.controller;

import com.info.springmongo.common.ResultCode;
import com.info.springmongo.dto.PageStudentDTO;
import com.info.springmongo.dto.StudentDTO;
import com.info.springmongo.entity.Student;
import com.info.springmongo.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/stu")
public class StudentController {

    private final StudentService studentService;

    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @PostMapping("/")
    public ResultCode saveStu(@Validated @RequestBody StudentDTO student) {
        Student stu = new Student();
        BeanUtils.copyProperties(student, stu);
        studentService.save(stu);
        return ResultCode.success();
    }

    @PutMapping("/{id}")
    public ResultCode updateStu(@Validated @RequestBody StudentDTO student, @PathVariable("id") Long id) {
        Student stu = new Student();
        BeanUtils.copyProperties(student, stu);
        stu.setId(id);
        studentService.update(stu);
        return ResultCode.success();
    }

    @DeleteMapping("/{id}")
    public ResultCode deleteStu(@PathVariable("id") Long id) {
        studentService.delete(id);
        return ResultCode.success();
    }

    @GetMapping("/")
    public ResultCode listStu(StudentDTO student) {
        Student stu = new Student();
        if (student == null) {
            stu = null;
        } else {
            BeanUtils.copyProperties(student, stu);
        }
        return ResultCode.success(studentService.getList(stu));
    }

    @GetMapping("/page")
    public ResultCode listByPageStu(@RequestBody PageStudentDTO student) {
        Student stu = new Student();
        BeanUtils.copyProperties(student, stu);
        return ResultCode.success(studentService.listByPage(stu, student.getPageNumber(), student.getPageSize()));
    }

}
